import os
import logging
import urllib
import urllib2
import paramiko
import tempfile

map_url = 'http://www.e-sports.or.kr/board/file/map/img/%s'

def image_download(filename):
    logger = logging.getLogger('ImageDownload')
    url = map_url % urllib.quote(filename.encode('utf-8'))
    logger.debug('Downloading %s' % url)

    file = urllib2.urlopen(url)
    image = ''.join(file.readlines())

    return image

class FileCopy(object):
    def __init__(self, directory):
        self.directory = directory
        self.logger = logging.getLogger('FileCopy')

    def copy(self, filename, data):
        full_filename = os.path.join(self.directory, filename)
        self.logger.debug('Writing data to %s' % full_filename)
        with open(full_filename, 'w') as f:
            f.write(data)
            f.close()

class SFTPUpload(object):
    def __init__(self, host, user, key_file, remote_directory):
        self.host = host
        self.user = user
        self.key_file = key_file
        self.remote_directory = remote_directory

    def upload(self, filename, data):
        self.key_file = os.path.expanduser(self.key_file)
        key = paramiko.RSAKey.from_private_key_file(self.key_file)
        remote_filename = os.path.join(self.remote_directory, filename)

        t = paramiko.Transport(self.host)

        try:
            t.start_client()
            t.auth_publickey(self.user, key)
            t.open_session()

            sftp = paramiko.SFTPClient.from_transport(t)

            with tempfile.NamedTemporaryFile() as f:
                f.write(data)
                f.flush()
                sftp.put(f.name, remote_filename)
        finally:
            t.close()




